package dp05.leertaak1.client;

import java.io.*;

public class Client
{

    public enum State {
        IDLE, OPEN, CLOSE, INSERT, UNDO, REDO, COMMIT, GET, TOTAL
    }

    private ServerConnection server;
    private BufferedReader stdIn;
    private boolean running = true;
    private State currentState = State.IDLE;

    public Client() throws IOException
    {
        server = new ServerConnection();
        stdIn = new BufferedReader(new InputStreamReader(System.in));

        String fromUser;
        while (running)
        {
            fromUser = stdIn.readLine();
            currentState = parseAction(fromUser);
            processRequest(fromUser);
        }
    }

    private void processRequest(String input) throws IOException
    {
        String fromServer;
        switch (currentState)
        {
            case OPEN:
                String[] parameters = input.split(" ");
                String host = "localhost";
                if (parameters.length > 1)
                {
                    host = parameters[1];
                }
                String status = server.connect(host);
                System.out.println(status);
                break;
            case CLOSE:
                fromServer = server.processAction(input);
                System.out.println(fromServer);
                running = false;
                server.close();
                break;
            case INSERT:
            case UNDO:
            case REDO:
            case COMMIT:
            case GET:
            case TOTAL:
                fromServer = server.processAction(input);
                System.out.println(fromServer);
                currentState = State.IDLE;
                break;
            default:
                System.out.println("Command not accepted");
        }

    }

    private State parseAction(String input)
    {
        input = input.trim();
        String action = input.split(" ")[0];
        for (State state : State.values())
        {
            if (action.equalsIgnoreCase(state.toString()))
            {
                return state;
            }
        }
        return State.IDLE;
    }

    public static void main(String[] args) throws IOException
    {
        new Client();
    }
}
